package model

import (
	"bytes"
	"fmt"
	"gorm.io/gorm"
	"iot-base/auth/utils"
)

type (
	UserRoleMode struct {
		db *gorm.DB
	}
	// UserRole  用户—角色表
	UserRole struct {
		ID     int64 `gorm:"primarykey" json:"id"`
		Uid    int64 `gorm:"index" json:"uid"`     // 用户ID
		RoleId int64 `gorm:"index" json:"role_id"` // 角色ID
	}
)

func NewUserRoleMode(db *gorm.DB) *UserRoleMode {
	return &UserRoleMode{
		db: db,
	}
}

func (m *UserRoleMode) FindUserRoleByUid(uid int64) (UserRole, error) {
	var userRole UserRole
	err := m.db.Where("uid = ?", uid).Take(&userRole).Error
	if err != nil {
		return userRole, err
	}
	return userRole, nil
}

func (m *UserRoleMode) AddUserRole(userRole *UserRole) error {
	userRole.ID = utils.GetUid()
	return m.db.Create(userRole).Error
}

// BatchSave 批量插入数据.
func (m *UserRoleMode) BatchSave(emps []UserRole) error {
	var buffer bytes.Buffer
	sql := "insert into user_roles (uid, role_id) values"
	if _, err := buffer.WriteString(sql); err != nil {
		return err
	}
	for i, e := range emps {
		if i == len(emps)-1 {
			buffer.WriteString(fmt.Sprintf("('%d','%d');", e.Uid, e.RoleId))
		} else {
			buffer.WriteString(fmt.Sprintf("('%d','%d'),", e.Uid, e.RoleId))
		}
	}
	return m.db.Exec(buffer.String()).Error
}

func (m *UserRoleMode) UpdateByUid(uid int64, userRole UserRole) (int64, error) {
	resp := m.db.Where("uid = ?", uid).Updates(userRole)
	return resp.RowsAffected, resp.Error
}

func (m *UserRoleMode) DelUserRole(uid int64, roleId int64) (int64, error) {
	session := m.db.Where("uid = ?", uid)
	if roleId != 0 {
		session.Where("role_id = ?", roleId)
	}
	resp := session.Delete(&UserRole{})
	return resp.RowsAffected, resp.Error
}
